﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using TIMETABLEASY.iCalManager;

using TIMETABLEASY.EasyCalendar.Model;
using TIMETABLEASY.EasyCalendar.Controler;

using TIMETABLEASY.TokenAuthentification;

namespace TIMETABLEASY
{

    public partial class Window1
    {
        //Initialisation des événements (pour la récupération dans le planning)
        private Events events = new Events();

        //Variables publiques utiles
        public string type;
        public int userid;
        public string usertype;
        public string userfirstname;
        public string usersurname;
        public string usercampus;
        public string userclass;
        public string usercursus;
        public string username;
        public string period;
        public int usernotepadenabled;
        public string usernotepadtext;
        public string userconnectionmode;

        //Initialisation de la base de données
        dbDataContext db_remote;
        Local_db db_local;

        public Window1()
        {

            #region Initialisation

            InitializeComponent();


            //Affichage ou non des boutons selon le type d'utilisateur
            SingletonTokenUser user_level = SingletonTokenUser.GetInstance();

            //On stocke les attributs courant de l'utilisateur dans les variables publiques
            usertype = user_level.User_level;
            userid = user_level.User_id;
            usercampus = user_level.User_campus;
            userclass = user_level.User_classe;
            username = user_level.User_login;
            usernotepadenabled = user_level.Notepad_enabled;
            usernotepadtext = user_level.Notepad_text;
            userfirstname = user_level.User_fistname;
            usersurname = user_level.User_surname;
            userconnectionmode = user_level.Database_mode;

            //Initialisation des datacontext pour la connexion
            if (userconnectionmode == "online")
            {
                db_remote = new dbDataContext();
            }

            else if (userconnectionmode == "offline")
            {
                db_local = new Local_db("Data Source=|DataDirectory|\\local_db.sdf;Max Database Size=2047");
            }

            switch (user_level.User_level)
            {
                case "administrators":
                    Planning_Manager.Visibility = Visibility.Visible;
                    Event_Manager.Visibility = Visibility.Visible;
                    User_Manager.Visibility = Visibility.Visible;
                    RibbonButton_Name_Class.Visibility = Visibility.Visible;
                    RibbonButton_Name_Campus.Visibility = Visibility.Visible;
                    break;
                case "managers":
                    Planning_Manager.Visibility = Visibility.Visible;
                    Event_Manager.Visibility = Visibility.Visible;
                    User_Manager.Visibility = Visibility.Visible;
                    Class_Manager.Visibility = Visibility.Visible;
                    Campus_Manager.Visibility = Visibility.Collapsed;

                    Admin_User.Visibility = Visibility.Collapsed;
                    Manager_User.Visibility = Visibility.Collapsed;

                    break;
                case "teacher":
                    Planning_Manager.Visibility = Visibility.Visible;
                    Event_Manager.Visibility = Visibility.Visible;
                    User_Manager.Visibility = Visibility.Collapsed;
                    Class_Manager.Visibility = Visibility.Collapsed;
                    Campus_Manager.Visibility = Visibility.Collapsed;
                    Room_Manager.Visibility = Visibility.Collapsed;
                    break;
                case "students":
                    Planning_Manager.Visibility = Visibility.Visible;
                    Event_Manager.Visibility = Visibility.Visible;
                    User_Manager.Visibility = Visibility.Collapsed;
                    Class_Manager.Visibility = Visibility.Collapsed;
                    Campus_Manager.Visibility = Visibility.Collapsed;
                    Room_Manager.Visibility = Visibility.Collapsed;
                    break;
                default:
                    Planning_Manager.Visibility = Visibility.Collapsed;
                    Event_Manager.Visibility = Visibility.Collapsed;
                    User_Manager.Visibility = Visibility.Collapsed;
                    Class_Manager.Visibility = Visibility.Collapsed;
                    Campus_Manager.Visibility = Visibility.Collapsed;
                    Room_Manager.Visibility = Visibility.Collapsed;
                    break;
            }

            //On affiche les données utilisateurs en haut de fenêtre
            welcome_login_text.Content = "Login : " + username;
            welcome_name_text.Content =  "Name : " + userfirstname + " " + usersurname;

            //On cache le gestionnaire avancé de plannings
            campus_expend_planning_combobox.Visibility = Visibility.Hidden;
            campus_label_expand.Visibility = Visibility.Hidden;
            cursus_expend_planning_combobox.Visibility = Visibility.Hidden;
            cursus_label_expand.Visibility = Visibility.Hidden;
            class_expend_planning_combobox.Visibility = Visibility.Hidden;
            class_label_expand.Visibility = Visibility.Hidden;
            period_expend_planning_combobox.Visibility = Visibility.Hidden;
            period_label_expand.Visibility = Visibility.Hidden;
            user_expend_planning_combobox.Visibility = Visibility.Hidden;
            user_label_expand.Visibility = Visibility.Hidden;
            type_user_expand_combobox.Visibility = Visibility.Hidden;
            type_user_label_expand.Visibility = Visibility.Hidden;

            type_user_expand_combobox.Items.Add("teacher");
            type_user_expand_combobox.Items.Add("administrator");
            type_user_expand_combobox.Items.Add("manager");
            type_user_expand_combobox.Items.Add("student");

            planning_expend_comboBox.Items.Add("University");
            planning_expend_comboBox.Items.Add("Campus");
            planning_expend_comboBox.Items.Add("Cursus");
            planning_expend_comboBox.Items.Add("Class");
            planning_expend_comboBox.Items.Add("User");
            planning_expend_comboBox.Items.Add("Period");


            //On cache les onglets au démarrage
            tab_calendar.Visibility = Visibility.Hidden;
            tab_event.Visibility = Visibility.Hidden;

            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;

            tab_class.Visibility = Visibility.Hidden;
            tab_campus.Visibility = Visibility.Hidden;
            tab_room.Visibility = Visibility.Hidden;

            //On cache les gestionnaires avancés d'utilisateur
            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            //Gestion du notepad
            if (usernotepadenabled == 0)
            {
                notepad_expander.IsExpanded = false;
                notes_textbox.Text = usernotepadtext;
            }

            else if (usernotepadenabled == 1)
            {
                notepad_expander.IsExpanded = true;
                notes_textbox.Text = usernotepadtext;
            }


            ///////////Initialisation des données///////////

            //Tri des événements selon les autorisations
            event_sort_combobox.Items.Add("All");
            event_sort_combobox.Items.Add("Personal");

            //Tri des teachers selon les autorisations
            teacher_sort_combobox.Items.Add("All");

            //Tri des students selon les autorisations
            student_sort_combobox.Items.Add("All");

            if (userconnectionmode == "online")
            {
                //Initialisation des listes déroulantes
                list_administrators(admin_listbox);
                list_students(student_listbox);
                list_managers(manager_listbox);
                list_teachers(teacher_listbox);
                list_campus(campus_listbox);
                list_campus(campus_listbox2);
                list_classes(class_listbox);
                list_rooms(room_listbox);
                list_cursus(cursus_listbox);


                //Initialisation des menus déroulants
                chargement_liste_campus_student();
                chargement_liste_campus_manager();
                chargement_liste_campus_teacher();
                chargement_liste_campus_event();
                chargement_liste_campus_room();
                chargement_liste_cursus_campus();

                chargement_campus_autorises_teacher();
                chargement_campus_autorises_student();
                chargement_campus_autorises_event();

                sort_events_by_campus();
                sort_teachers_by_campus();
                sort_students_by_campus();


            }

            else if (userconnectionmode == "offline")
            {
                //Initialisation des listes déroulantes
                list_administrators_offline(admin_listbox);
                list_students_offline(student_listbox);
                list_managers_offline(manager_listbox);
                list_teachers_offline(teacher_listbox);
                list_campus_offline(campus_listbox);
                list_campus_offline(campus_listbox2);
                list_classes_offline(class_listbox);
                list_rooms_offline(room_listbox);
                list_cursus_offline(cursus_listbox);

                //Initialisation des menus déroulants
                chargement_liste_campus_student_offline();
                chargement_liste_campus_manager_offline();
                chargement_liste_campus_teacher_offline();
                chargement_liste_campus_event_offline();
                chargement_liste_campus_room_offline();
                chargement_liste_cursus_campus_offline();

                chargement_campus_autorises_teacher_offline();
                chargement_campus_autorises_student_offline();
                chargement_campus_autorises_event_offline();

                sort_events_by_campus_offline();
                sort_teachers_by_campus_offline();
                sort_students_by_campus_offline();

            }


            #endregion
        }

        #region Menu contextuel de l'application

        //On exporte le planning en iCal
        private void ExportIcalCommand(object sender, RoutedEventArgs e)
        {
            ICalSavWindows iCal = new ICalSavWindows();
            iCal.Show();
        }

        //On quitte l'application
        private void ExitApplication(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //On affiche le "A propos"
        private void DisplayAbout(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("This application was developed by : \nMaxime Rastello\nBryce Bronner\nThierry Coffy\nYohann Lavigne\n\nCopyright © 2010 - All rights reserved");
        }

        //On redémarre l'application
        private void restart()
        {

            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
            Application.Current.Shutdown();
        }

        //On ouvre le panneau des options
        private void OpenOptions(object sender, RoutedEventArgs e)
        {
            Options option = new Options();
            option.Show();
        }

        private void save_notepad()
        {
            switch (usertype)
            {
                case "administrators":

                    administrators admin1 = (from e in db_remote.administrators
                                             where e.id == userid
                                             select e).FirstOrDefault();

                    admin1.notepad_text = notes_textbox.Text;

                    db_remote.SubmitChanges();

                    break;

                case "managers":

                    managers manager1 = (from e in db_remote.managers
                                         where e.id == userid
                                         select e).FirstOrDefault();

                    manager1.notepad_text = notes_textbox.Text;

                    db_remote.SubmitChanges();

                    break;

                case "students":

                    students student1 = (from e in db_remote.students
                                         where e.id == userid
                                         select e).FirstOrDefault();

                    student1.notepad_text = notes_textbox.Text;

                    db_remote.SubmitChanges();

                    break;

                case "teacher":

                    teacher teacher1 = (from e in db_remote.teacher
                                        where e.id == userid
                                        select e).FirstOrDefault();

                    teacher1.notepad_text = notes_textbox.Text;

                    db_remote.SubmitChanges();

                    break;

                default:
                    break;

            }

            tick_saved_notepad_image.Visibility = Visibility.Visible;

        }


        private void save_notepad_offline()
        {
            switch (usertype)
            {
                case "administrators":

                    Administrators admin1 = (from e in db_local.Administrators
                                             where e.Id == userid
                                             select e).FirstOrDefault();

                    admin1.Notepad_text = notes_textbox.Text;

                    db_local.SubmitChanges();

                    break;

                case "managers":

                    Managers manager1 = (from e in db_local.Managers
                                         where e.Id == userid
                                         select e).FirstOrDefault();

                    manager1.Notepad_text = notes_textbox.Text;

                    db_local.SubmitChanges();

                    break;

                case "students":

                    Students student1 = (from e in db_local.Students
                                         where e.Id == userid
                                         select e).FirstOrDefault();

                    student1.Notepad_text = notes_textbox.Text;

                    db_local.SubmitChanges();

                    break;

                case "teacher":

                    Teacher teacher1 = (from e in db_local.Teacher
                                        where e.Id == userid
                                        select e).FirstOrDefault();

                    teacher1.Notepad_text = notes_textbox.Text;

                    db_local.SubmitChanges();

                    break;

                default:
                    break;

            }

            tick_saved_notepad_image.Visibility = Visibility.Visible;

        }

        #endregion


        //Controles

        #region controles administrateur
        //////////////////////////////////CONTROLES ADMINISTRATEUR///////////////////////////

        private void admin_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (admin_login_textbox.Text != "")
            {
                try
                {
                    string name_temp = admin_login_textbox.Text.ToLower();

                    bool test = admin_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_administrators();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_administrators_offline();
                        }

                        MessageBox.Show("L'utilisateur a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("L'utilisateur entré existe déjà");

                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors de la création de l'utilisateur");
                    MessageBox.Show(error.ToString());
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom d'utilisateur");
            }
        }

        private void admin_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_administrators();
                }
                else if (userconnectionmode == "offline")
                {
                    update_administrators_offline();
                }

                MessageBox.Show("L'utilisateur a été modifié avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de l'utilisateur");
            }

        }

        private void admin_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_administrators();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_administrators_offline();
                }

                MessageBox.Show("L'utilisateur a été supprimé avec succès");
            }
            catch (Exception error)
            {
                MessageBox.Show("Erreur lors de la suppression de l'utilisateur : " + error.ToString());
            }
        }

        private void admin_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = admin_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = admin_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_administrators(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_administrators_offline(param);
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste");
                }
            }

        }
        #endregion

        #region controles students
        //////////////////////////CONTROLES STUDENTS///////////////////////////////////////

        private void student_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (student_login_textbox.Text != "")
            {
                try
                {
                    string name_temp = student_login_textbox.Text.ToLower();

                    bool test = student_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_students();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_students_offline();
                        }
                        
                        MessageBox.Show("L'utilisateur a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("L'utilisateur entré existe déjà");

                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors de la création de l'utilisateur");
                    MessageBox.Show(error.ToString());
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom d'utilisateur");
            }
        }

        private void student_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_students();
                }
                else if (userconnectionmode == "offline")
                {
                    update_students_offline();
                }

                MessageBox.Show("L'utilisateur a été modifié avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de l'utilisateur");
            }

        }

        private void student_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_students();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_students_offline();
                }

                MessageBox.Show("L'utilisateur a été supprimé avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la suppression de l'utilisateur");
            }
        }

        private void student_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = student_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = student_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_students(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_students_offline(param);
                    }
                    
                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste");
                }
            }

        }


        private void student_sort_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    sort_students_by_campus();
                }
                else if (userconnectionmode == "offline")
                {
                    sort_students_by_campus_offline();
                }
                
            }
            catch (Exception)
            {

            }
        }



        #endregion

        #region controles managers
        //////////////////////////CONTROLES MANAGERS///////////////////////////////////////

        private void manager_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (manager_login_textbox.Text != "" && manager_campus_listbox.SelectedItems.Count != 0)
            {
                try
                {
                    string name_temp = manager_login_textbox.Text.ToLower();

                    bool test = manager_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_managers();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_managers_offline();
                        }

                        MessageBox.Show("L'utilisateur a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("L'utilisateur entré existe déjà");
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur lors de la création de l'utilisateur");
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom d'utilisateur et/ou un campus.");
            }
        }

        private void manager_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_managers();
                }
                else if (userconnectionmode == "offline")
                {
                    update_managers_offline();
                }

                MessageBox.Show("L'utilisateur a été modifié avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de l'utilisateur");
            }

        }

        private void manager_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_managers();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_managers_offline();
                }

                MessageBox.Show("L'utilisateur a été supprimé avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la suppression de l'utilisateur");
            }
        }

        private void manager_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = manager_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = manager_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_managers(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_managers_offline(param);
                    }
                    
                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste");
                }
            }

        }


        #endregion

        #region controles campus
        //////////////////////////////////CONTROLES CAMPUS//////////////////////////////////

        private void campus_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (campus_name_textbox.Text != "")
            {
                try
                {
                    string name_temp = campus_name_textbox.Text.ToLower();

                    bool test = campus_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_campus();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_campus_offline();
                        }

                        MessageBox.Show("L'élément a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("L'élément entré existe déjà");

                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors de la création de l'élément");
                    MessageBox.Show(error.ToString());
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom d'élément");
            }
        }

        private void campus_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_campus();
                }
                else if (userconnectionmode == "offline")
                {
                    update_campus_offline();
                }

                MessageBox.Show("L'élément a été modifié avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de l'élément");
            }

        }

        private void campus_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_campus();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_campus_offline();
                }

                MessageBox.Show("L'élément a été supprimé avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la suppression de l'élément");
            }
        }

        private void campus_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = campus_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = campus_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_campus(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_campus_offline(param);
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste");
                }
            }
        }


        private void campus_cursus_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    chargement_liste_period_campus();
                }
                else if (userconnectionmode == "offline")
                {
                    chargement_liste_period_campus_offline();
                }

            }
            catch (Exception error)
            {

                MessageBox.Show("Erreur dans le chargement des périodes : " + error.ToString());
            }

        }

        private void campus_periodButton_Click(object sender, RoutedEventArgs e)
        {

            bool compteur = campus_period_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    if (userconnectionmode == "online")
                    {
                        set_periods();
                    }
                    else if (userconnectionmode == "offline")
                    {
                        set_periods_offline();
                    }

                    MessageBox.Show("Les périodes ont été définies avec succès");
                }
                catch (Exception)
                {

                    MessageBox.Show("Erreur lors de la définition des périodes. Avez-vous sélectionné un campus et/ou une période ?");
                }
            }
        }


        #endregion

        #region controles classes
        //////////////////////////////////CONTROLES CLASS//////////////////////////////////////

        private void class_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (class_name_textbox.Text != "")
            {
                try
                {
                    string name_temp = class_name_textbox.Text.ToLower();

                    bool test = class_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_classes();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_classes_offline();
                        }

                        MessageBox.Show("L'élément a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("L'élément entré existe déjà");

                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors de la création de l'élément");
                    MessageBox.Show(error.ToString());
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom d'élément");
            }
        }

        private void class_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_classes();
                }
                else if (userconnectionmode == "offline")
                {
                    update_classes_offline();
                }

                MessageBox.Show("L'élément a été modifié avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de l'élément");
            }

        }

        private void class_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_classes();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_classes_offline();
                }

                MessageBox.Show("L'élément a été supprimé avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la suppression de l'élément");
            }
        }

        private void class_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = class_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = class_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_classes(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_classes_offline(param);
                    }
                    
                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste : " + error.ToString());
                }
            }

        }

        private void campus_listbox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (userconnectionmode == "online")
            {
                list_classes(class_listbox);
            }
            else if (userconnectionmode == "offline")
            {
                list_classes_offline(class_listbox);
            }

        }

        #endregion

        #region controles teachers
        //////////////////////////CONTROLES TEACHERS///////////////////////////////////////

        private void teacher_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (teacher_login_textbox.Text != "")
            {
                try
                {
                    string name_temp = teacher_login_textbox.Text.ToLower();

                    bool test = teacher_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_teachers();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_teachers_offline();
                        }

                        MessageBox.Show("L'utilisateur a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("L'utilisateur entré existe déjà");

                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors de la création de l'utilisateur");
                    MessageBox.Show(error.ToString());
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom d'utilisateur");
            }
        }

        private void teacher_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_teachers();
                }
                else if (userconnectionmode == "offline")
                {
                    update_teachers_offline();
                }

                MessageBox.Show("L'utilisateur a été modifié avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de l'utilisateur");
            }

        }

        private void teacher_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_teachers();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_teachers_offline();
                }

                MessageBox.Show("L'utilisateur a été supprimé avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la suppression de l'utilisateur");
            }
        }

        private void teacher_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = teacher_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = teacher_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_teachers(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_teachers_offline(param);
                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste");
                    MessageBox.Show(error.ToString());
                }
            }

        }


        private void teacher_campus_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (userconnectionmode == "online")
            {
                chargement_liste_classe_teacher();
            }
            else if (userconnectionmode == "offline")
            {
                chargement_liste_classe_teacher_offline();
            }
        }

        private void teacher_status_checkbox_Checked(object sender, RoutedEventArgs e)
        {
            //On affiche les combobox
            teacher_campus_combobox.Visibility = Visibility.Visible;
            teacher_class_combobox.Visibility = Visibility.Visible;
            //On affiche les labels
            teacher_campus_label.Visibility = Visibility.Visible;
            teacher_class_label.Visibility = Visibility.Visible;
        }

        private void teacher_status_checkbox_Unchecked(object sender, RoutedEventArgs e)
        {
            //On cache les combobox
            teacher_campus_combobox.Visibility = Visibility.Hidden;
            teacher_class_combobox.Visibility = Visibility.Hidden;
            //On cache les labels
            teacher_campus_label.Visibility = Visibility.Hidden;
            teacher_class_label.Visibility = Visibility.Hidden;
        }


        private void teacher_sort_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    sort_teachers_by_campus();
                }
                else if (userconnectionmode == "offline")
                {
                    sort_teachers_by_campus_offline();
                }
            }
            catch (Exception)
            {

            }
        }




        #endregion

        #region controles events
        //////////////////////////CONTROLES EVENTS///////////////////////////////////////

        private void event_addButton_Click(object sender, RoutedEventArgs e)
        {

            // oblige l'utilisateur a remplir tout les champs étoilé
            if (event_name_textbox.Text != "" && event_priority_combobox.SelectedValue != null && event_type_combobox.SelectedValue != null
                && event_startingdate_combobox.SelectedValue != null && event_endingdate_combobox.SelectedValue != null
                   && event_startingdate_datepicker.SelectedDate != null && event_endingdate_datepicker.SelectedDate != null)
            {
                try
                {
                    string name_temp = event_name_textbox.Text.ToLower();

                    bool test = event_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            if (add_events())
                            {
                                MessageBox.Show("The event was successfully added.");
                            }

                            else
                            {
                                MessageBox.Show("You're not allowed to create this event.");
                            }
                        }

                        else if (userconnectionmode == "offline")
                        {
                            if (add_events_offline())
                            {
                                MessageBox.Show("The event was successfully added.");
                            }

                            else
                            {
                                MessageBox.Show("You're not allowed to create this event.");
                            }
                        }

                    }
                    else
                    {
                        MessageBox.Show("The event already exists.");
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error during the event creation.");
                }
            }
            else
            {
                MessageBox.Show("Please fill all mandatory fields.");
            }
        }

        private void event_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_events();
                }
                else if (userconnectionmode == "offline")
                {
                    update_events_offline();
                }

                MessageBox.Show("The event was successfully updated.");
            }
            catch (Exception)
            {
                MessageBox.Show("Error during the event update.");
            }
        }

        private void event_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    delete_events();
                }
                else if (userconnectionmode == "offline")
                {
                    delete_events_offline();
                }

                MessageBox.Show("The event was successfully deleted.");
            }
            catch (Exception)
            {
                MessageBox.Show("Error during the event deletion.");
            }
        }

        

        private void event_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = event_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = event_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_events(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_events_offline(param);
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Error during loading. Please try again.");
                }
            }
        }



        private void event_more_checkbox_Checked(object sender, RoutedEventArgs e)
        {
            //On affiche les élements optionnels
            event_participant_expander.Visibility = Visibility.Visible;
            event_location_expander.Visibility = Visibility.Visible;
            event_work_expander.Visibility = Visibility.Visible;

            event_help_image.Visibility = Visibility.Hidden;

        }

        private void event_more_checkbox_Unchecked(object sender, RoutedEventArgs e)
        {
            //On cache les élements optionnels
            event_participant_expander.Visibility = Visibility.Hidden;
            event_location_expander.Visibility = Visibility.Hidden;
            event_work_expander.Visibility = Visibility.Hidden;

            event_help_image.Visibility = Visibility.Visible;

        }



        private void event_participantname_combobox_MouseEnter(object sender, MouseEventArgs e)
        {
            if (event_participanttype_combobox.Text != "")
            {
                if (userconnectionmode == "online")
                {
                    chargement_liste_login_event();
                }
                else if (userconnectionmode == "offline")
                {
                    chargement_liste_login_event_offline();
                }
            }
        }


        private void event_period_combobox_MouseEnter(object sender, MouseEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    list_periods();
                }
                else if (userconnectionmode == "offline")
                {
                    list_periods_offline();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("No period is available.");
            }
        }

        

        private void event_sort_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    sort_events_by_campus();
                }
                else if (userconnectionmode == "offline")
                {
                    sort_events_by_campus_offline();
                }
            }
            catch (Exception error)
            {

                MessageBox.Show("Error during event displaying : " + error.ToString());
            }
        }

        private void event_subject_combobox_MouseEnter(object sender, MouseEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    list_subjects();
                }
                else if (userconnectionmode == "offline")
                {
                    list_subjects_offline();
                }

            }
            catch (Exception)
            {

                MessageBox.Show("No subject is available.");
            }
        }

        private void event_campus_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (userconnectionmode == "online")
            {
                chargement_liste_classe_event();
                chargement_liste_room_event();
            }
            else if (userconnectionmode == "offline")
            {
                chargement_liste_classe_event_offline();
                chargement_liste_room_event_offline();
            }
        }


        #endregion

        #region controles salles
        //////////////////////////////////CONTROLES SALLES//////////////////////////////////

        private void room_addButton_Click(object sender, RoutedEventArgs e)
        {
            if (room_name_textbox.Text != "")
            {
                try
                {
                    string name_temp = room_name_textbox.Text.ToLower();

                    bool test = room_listbox.Items.Contains(name_temp);

                    if (test == false)
                    {
                        if (userconnectionmode == "online")
                        {
                            add_rooms();
                        }
                        else if (userconnectionmode == "offline")
                        {
                            add_rooms_offline();
                        }

                        MessageBox.Show("La salle a été ajouté avec succès");
                    }
                    else
                    {
                        MessageBox.Show("La salle entrée existe déjà");

                    }

                }
                catch (Exception error)
                {
                    MessageBox.Show("Erreur lors de la création de la salle");
                    MessageBox.Show(error.ToString());
                }
            }
            else
            {
                MessageBox.Show("Merci de rentrer un nom de salle");
            }
        }

        private void room_updateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_rooms();
                }
                else if (userconnectionmode == "offline")
                {
                    update_rooms_offline();
                }

                MessageBox.Show("La salle a été modifiée avec succès");
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la modification de la salle");
            }
        }

        private void room_deleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    if (delete_rooms())
                    {
                        MessageBox.Show("La salle a été supprimée avec succès");
                    }
                }
                else if (userconnectionmode == "offline")
                {
                    if (delete_rooms_offline())
                    {
                        MessageBox.Show("La salle a été supprimée avec succès");
                    }
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Erreur lors de la suppression de la salle");
            }
        }

        private void room_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = room_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    String param = room_listbox.SelectedValue.ToString();

                    if (userconnectionmode == "online")
                    {
                        display_rooms(param);
                    }
                    else if (userconnectionmode == "offline")
                    {
                        display_rooms_offline(param);
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Erreur lors du chargement de la liste");
                }
            }
        }


        #endregion

        #region controles bandeau
        //////////////////////////CONTROLES BANDEAU///////////////////////////////////////

        private void OnCanExecute(object target, CanExecuteRoutedEventArgs args)
        {
            args.CanExecute = true;

        }
        // Interaction avec un bouton.
        private void RibbonButton_Click_planning(object sender, RoutedEventArgs e)
        {
            tab_event.Visibility = Visibility.Hidden;
            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;
            tab_class.Visibility = Visibility.Hidden;
            tab_campus.Visibility = Visibility.Hidden;

            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            tab_room.Visibility = Visibility.Hidden;

            tab_calendar.Visibility = Visibility.Visible;
            planning_manager_expender.Visibility = Visibility.Visible;
            tabControl1.SelectedItem = tab_calendar;

            notepad_expander.Visibility = Visibility.Collapsed;

        }

        private void RibbonButton_Name_Event_Click(object sender, RoutedEventArgs e)
        {
            tab_calendar.Visibility = Visibility.Hidden;
            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;
            tab_class.Visibility = Visibility.Hidden;
            tab_campus.Visibility = Visibility.Hidden;

            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            tab_room.Visibility = Visibility.Hidden;
            planning_manager_expender.Visibility = Visibility.Hidden;
            tab_event.Visibility = Visibility.Visible;

            tabControl1.SelectedItem = tab_event;

            notepad_expander.Visibility = Visibility.Visible;

        }

        private void RibbonButton_User_Manager_Click(object sender, RoutedEventArgs e)
        {
            Admin_User.Visibility = Visibility.Visible;
            Manager_User.Visibility = Visibility.Visible;
            Teacher_User.Visibility = Visibility.Visible;
            Student_User.Visibility = Visibility.Visible;

            planning_manager_expender.Visibility = Visibility.Hidden;

            notepad_expander.Visibility = Visibility.Visible;

        }

        private void RibbonButton_Admin_Click(object sender, RoutedEventArgs e)
        {
            tabControl1.SelectedItem = tab_admin;
        }

        private void RibbonButton_Manager_Click(object sender, RoutedEventArgs e)
        {
            tabControl1.SelectedItem = tab_manager;
        }

        private void RibbonButton_Teacher_Click(object sender, RoutedEventArgs e)
        {
            tabControl1.SelectedItem = tab_teacher;
        }

        private void RibbonButton_Student_Click(object sender, RoutedEventArgs e)
        {
            tabControl1.SelectedItem = tab_student;
        }


        private void RibbonButton_Name_Class_Click(object sender, RoutedEventArgs e)
        {
            tab_calendar.Visibility = Visibility.Hidden;
            tab_event.Visibility = Visibility.Hidden;
            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;

            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            tab_campus.Visibility = Visibility.Hidden;
            tab_room.Visibility = Visibility.Hidden;
            planning_manager_expender.Visibility = Visibility.Hidden;
            tab_class.Visibility = Visibility.Visible;

            tabControl1.SelectedItem = tab_class;

            notepad_expander.Visibility = Visibility.Visible;
        }

        private void RibbonButton_Name_Campus_Click(object sender, RoutedEventArgs e)
        {
            tab_calendar.Visibility = Visibility.Hidden;
            tab_event.Visibility = Visibility.Hidden;
            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;

            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            tab_room.Visibility = Visibility.Hidden;
            tab_class.Visibility = Visibility.Hidden;
            planning_manager_expender.Visibility = Visibility.Hidden;
            tab_campus.Visibility = Visibility.Visible;

            tabControl1.SelectedItem = tab_campus;

            notepad_expander.Visibility = Visibility.Visible;
        }

        private void RibbonButton_Name_Room_Click(object sender, RoutedEventArgs e)
        {

            tab_calendar.Visibility = Visibility.Hidden;
            tab_event.Visibility = Visibility.Hidden;
            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;

            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            tab_class.Visibility = Visibility.Hidden;
            tab_campus.Visibility = Visibility.Hidden;
            planning_manager_expender.Visibility = Visibility.Hidden;
            tab_room.Visibility = Visibility.Visible;

            tabControl1.SelectedItem = tab_room;

            notepad_expander.Visibility = Visibility.Visible;

        }

        private void RibbonButton_Name_Cursus_Click(object sender, RoutedEventArgs e)
        {

            tab_calendar.Visibility = Visibility.Hidden;
            tab_event.Visibility = Visibility.Hidden;
            tab_admin.Visibility = Visibility.Hidden;
            tab_manager.Visibility = Visibility.Hidden;
            tab_student.Visibility = Visibility.Hidden;
            tab_teacher.Visibility = Visibility.Hidden;

            Admin_User.Visibility = Visibility.Collapsed;
            Manager_User.Visibility = Visibility.Collapsed;
            Teacher_User.Visibility = Visibility.Collapsed;
            Student_User.Visibility = Visibility.Collapsed;

            tab_class.Visibility = Visibility.Hidden;
            tab_campus.Visibility = Visibility.Hidden;
            tab_room.Visibility = Visibility.Hidden;
            planning_manager_expender.Visibility = Visibility.Hidden;
            tab_cursus.Visibility = Visibility.Visible;

            tabControl1.SelectedItem = tab_cursus;

            notepad_expander.Visibility = Visibility.Visible;

        }

        #endregion

        #region controles cursus/periode/subject

        //Selection of an Item of cursus_listBox
        private void cursus_listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = cursus_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    if (userconnectionmode == "online")
                    {
                        populate_cursus_fields();
                        list_periods(periods_listbox, get_id_cursus(cursus_listbox.SelectedValue.ToString()));
                        subjects_listbox.Items.Clear();
                        clean_subject_fields();
                        clean_period_fields();
                    }
                    else if (userconnectionmode == "offline")
                    {
                        populate_cursus_fields_offline();
                        list_periods_offline(periods_listbox, get_id_cursus_offline(cursus_listbox.SelectedValue.ToString()));
                        subjects_listbox.Items.Clear();
                        clean_subject_fields_offline();
                        clean_period_fields_offline();
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Error during loading. Please try again.");
                }
            }
        }

        //Selection of an Item of periods_listBox
        private void periods_listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool compteur = periods_listbox.Items.IsEmpty;

            if (!compteur)
            {
                try
                {
                    if (userconnectionmode == "online")
                    {
                        populate_period_fields();

                        int cursus_id_temp = (from f in db_remote.cursus
                                              where f.name == cursus_listbox.SelectedValue.ToString()
                                              select f.id).FirstOrDefault();

                        list_subjects(subjects_listbox, get_id_period(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                        clean_subject_fields();
                    }

                    else if (userconnectionmode == "offline")
                    {
                        populate_period_fields_offline();

                        int cursus_id_temp = (from f in db_local.Cursus
                                              where f.Name == cursus_listbox.SelectedValue.ToString()
                                              select f.Id).FirstOrDefault();

                        list_subjects_offline(subjects_listbox, get_id_period_offline(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                        clean_subject_fields_offline();
                    }

                }
                catch (Exception)
                {
                    MessageBox.Show("Error during the loading. Please try again.");
                }
            }

        }

        //Selection of an Item of subjects_listBox
        private void subjects_listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!subjects_listbox.Items.IsEmpty)
            {
                if (userconnectionmode == "online")
                {
                    populate_subject_fields();
                }

                else if (userconnectionmode == "offline")
                {
                    populate_subject_fields_offline();
                }

            }

        }

        //Deleting of selected subject
        private void delete_subjects_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!subjects_listbox.Items.IsEmpty)
                {
                    if (userconnectionmode == "online")
                    {
                        delete_subject(get_id_subject(subjects_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString(), periods_listbox.SelectedValue.ToString()));
                        clean_subject_fields();
                    }

                    else if (userconnectionmode == "offline")
                    {
                        delete_subject_offline(get_id_subject(subjects_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString(), periods_listbox.SelectedValue.ToString()));
                        clean_subject_fields_offline();
                    }

                    MessageBox.Show("The cursus was successfully deleted.");
                }
            }
            catch (Exception)
            {

                MessageBox.Show("Error during subject deletion.");
            }

        }

        //Deleting of selected period
        private void delete_periods_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!periods_listbox.Items.IsEmpty)
                {
                    if (userconnectionmode == "online")
                    {
                        int cursus_id_temp = (from f in db_remote.cursus
                                              where f.name == cursus_listbox.SelectedValue.ToString()
                                              select f.id).FirstOrDefault();

                        delete_period(get_id_period(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                        clean_period_fields();
                        clean_subject_fields();
                    }

                    else if (userconnectionmode == "offline")
                    {
                        int cursus_id_temp = (from f in db_local.Cursus
                                              where f.Name == cursus_listbox.SelectedValue.ToString()
                                              select f.Id).FirstOrDefault();

                        delete_period_offline(get_id_period_offline(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                        clean_period_fields_offline();
                        clean_subject_fields_offline();
                    }

                    MessageBox.Show("The period was successfully deleted.");
                }
            }
            catch (Exception)
            {
                
                MessageBox.Show("Error during period deletion.");
            }

        }

        //Deleting of selected cursus
        private void delete_cursus_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!cursus_listbox.Items.IsEmpty)
                {
                    if (userconnectionmode == "online")
                    {
                        delete_cursus(get_id_cursus(cursus_listbox.SelectedValue.ToString()));
                        clean_cursus_fields();
                        clean_period_fields();
                        clean_subject_fields();
                    }

                    else if (userconnectionmode == "offline")
                    {
                        delete_cursus_offline(get_id_cursus_offline(cursus_listbox.SelectedValue.ToString()));
                        clean_cursus_fields_offline();
                        clean_period_fields_offline();
                        clean_subject_fields_offline();
                    }

                    MessageBox.Show("The cursus was successfully deleted.");
                }

            }
            catch (Exception)
            {

                MessageBox.Show("Error during cursus deletion.");
            }

        }

        //Creating of a new cursus
        private void create_cursus_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    add_cursus();
                    list_cursus(cursus_listbox);
                    clean_period_fields();
                    clean_subject_fields();
                }

                else if (userconnectionmode == "offline")
                {
                    add_cursus_offline();
                    list_cursus_offline(cursus_listbox);
                    clean_period_fields_offline();
                    clean_subject_fields_offline();
                }

                MessageBox.Show("The cursus was successfully added.");
            }
            catch (Exception)
            {
                
                MessageBox.Show("Error during cursus add.");
            }

        }

        //Creating of a new period
        private void create_periods_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    add_period();
                    list_periods(periods_listbox, get_id_cursus(cursus_listbox.SelectedValue.ToString()));
                    clean_subject_fields();
                }

                else if (userconnectionmode == "offline")
                {
                    add_period_offline();
                    list_periods_offline(periods_listbox, get_id_cursus_offline(cursus_listbox.SelectedValue.ToString()));
                    clean_subject_fields_offline();
                }

                MessageBox.Show("The period was successfully added.");
            }
            catch (Exception)
            {

                MessageBox.Show("Error during period add.");
            }

        }

        //Creating of a new subject
        private void create_subjects_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    add_subject();

                    int cursus_id_temp = (from f in db_remote.cursus
                                          where f.name == cursus_listbox.SelectedValue.ToString()
                                          select f.id).FirstOrDefault();

                    list_subjects(subjects_listbox, get_id_period(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                }

                else if (userconnectionmode == "offline")
                {
                    add_subject_offline();

                    int cursus_id_temp = (from f in db_local.Cursus
                                          where f.Name == cursus_listbox.SelectedValue.ToString()
                                          select f.Id).FirstOrDefault();

                    list_subjects_offline(subjects_listbox, get_id_period_offline(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                }

                MessageBox.Show("The subject was successfully added.");
            }
            catch (Exception)
            {

                MessageBox.Show("Error during subject add.");
            }

        }

        //Updating of a cursus
        private void refresh_cursus_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_cursus();
                    list_cursus(cursus_listbox);
                    clean_period_fields();
                    clean_subject_fields();
                }

                else if (userconnectionmode == "offline")
                {
                    update_cursus_offline();
                    list_cursus_offline(cursus_listbox);
                    clean_period_fields_offline();
                    clean_subject_fields_offline();
                }

                MessageBox.Show("The cursus was successfully updated.");
            }
            catch (Exception)
            {

                MessageBox.Show("Error during cursus update.");
            }

        }

        //Updating of a period
        private void refresh_periods_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_period();
                    list_periods(periods_listbox, get_id_cursus(cursus_listbox.SelectedValue.ToString()));
                    clean_subject_fields();
                }

                else if (userconnectionmode == "offline")
                {
                    update_period_offline();
                    list_periods_offline(periods_listbox, get_id_cursus_offline(cursus_listbox.SelectedValue.ToString()));
                    clean_subject_fields_offline();
                }

                MessageBox.Show("The period was successfully updated.");
            }
            catch (Exception)
            {

                MessageBox.Show("Error during period update.");
            }

        }

        //Updating of a subject
        private void refresh_subects_button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    update_subject();

                    int cursus_id_temp = (from f in db_remote.cursus
                                          where f.name == cursus_listbox.SelectedValue.ToString()
                                          select f.id).FirstOrDefault();

                    list_subjects(subjects_listbox, get_id_period(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                }

                else if (userconnectionmode == "offline")
                {
                    update_subject();

                    int cursus_id_temp = (from f in db_local.Cursus
                                          where f.Name == cursus_listbox.SelectedValue.ToString()
                                          select f.Id).FirstOrDefault();

                    list_subjects_offline(subjects_listbox, get_id_period_offline(cursus_id_temp + "?" + periods_listbox.SelectedValue.ToString(), cursus_listbox.SelectedValue.ToString()));
                }

                MessageBox.Show("The subject was successfully updated.");
            }
            catch (Exception)
            {

                MessageBox.Show("Error during subject update.");
            }
}




        #endregion


        #region controles expander

        private void planning_expend_comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    display_items_expander();
                }

                else if (userconnectionmode == "offline")
                {
                    display_items_expander_offline();
                }


            }
            catch (Exception)
            {
                MessageBox.Show("Erreur dans le chargement des filtres. Veuillez contacter l'administrateur");
            }

        }


        private void type_user_expand_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    display_user_type_expander();
                }

                else if (userconnectionmode == "offline")
                {
                    display_user_type_expander_offline();
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Erreur dans le chargement des filtres. Veuillez contacter l'administrateur");
            }
        }

        private void submit_planning_expend_Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    submit_new_planning();
                }

                else if (userconnectionmode == "offline")
                {
                    submit_new_planning_offline();
                }
                timeTableView.jump_2_x_week(0);
            }
            catch (Exception)
            {
                MessageBox.Show("Erreur dans le chargement du planning. Veuillez contacter l'administrateur");
            }
        }

        private void campus_expend_planning_combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    display_campus_expander();
                }

                else if (userconnectionmode == "offline")
                {
                    display_campus_expander_offline();
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Erreur dans le chargement des filtres. Veuillez contacter l'administrateur");
            }
        }

        private void planning_manager_expender_Expanded(object sender, RoutedEventArgs e)
        {
            BrushConverter converter = new BrushConverter();
            planning_manager_expender.BorderBrush = converter.ConvertFromString("#FF6593CF") as Brush;
        }

        private void planning_manager_expender_Collapsed(object sender, RoutedEventArgs e)
        {
            BrushConverter converter = new BrushConverter();
            planning_manager_expender.BorderBrush = converter.ConvertFromString("Transparent") as Brush;
        }


        #endregion

        #region controles divers

        private void logout_image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            restart();
        }


        private void save_notepad_image_MouseEnter(object sender, MouseEventArgs e)
        {
            try
            {
                if (userconnectionmode == "online")
                {
                    save_notepad();
                }

                else if (userconnectionmode == "offline")
                {
                    save_notepad_offline();
                }

            }
            catch (Exception)
            {

                MessageBox.Show("Impossible to save the notepad");
            }
        }
        

        #endregion



    }
}